package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.entity.AllMoneyBean;
import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.view.ChartProp;
import cn.com.xinjinfu.pdoulcProduct.view.ChartView;

/**
 * 总资产
 * Created by android-adt on 2016/3/30.
 */
public class AllMoneyActivity extends BaseActivity {
    private RequestQueue requen;
    private TextView bidding_money, tv_balance, invest_freeze, withdraw_freeze, zong_income;
    private AllMoneyBean allMoneyBean;
    private ArrayList<TestBean> beanLists;
    private ChartView mChartView;
    private Dialog dg;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_all_money);
        TitleManager.showTitleWhite(this, "总资产", "");
        beanLists = new ArrayList<>();
        mChartView = (ChartView) this.findViewById(R.id.chartView);
        mChartView.setAntiAlias(true);
//        mChartView.setCenter(new Point(360, 240));
        mChartView.setStartAngle(0);
        mChartView.setWizardLineLength(80.0f);

        zong_income = (TextView) findViewById(R.id.zong_income);
        bidding_money = (TextView) findViewById(R.id.bidding_money);
        tv_balance = (TextView) findViewById(R.id.tv_balance);
        invest_freeze = (TextView) findViewById(R.id.invest_freeze);
        withdraw_freeze = (TextView) findViewById(R.id.withdraw_freeze);
        requen = Volley.newRequestQueue(this);
        if (!DataHandler.isNetworkConnected(this)) {
            if (SharedPreferencesUtils.getUserInfo(this, "allMoneyBean") != "") {
                allMoneyBean = JSON.parseObject(SharedPreferencesUtils.getUserInfo(this, "allMoneyBean"), AllMoneyBean.class);
                if (allMoneyBean != null) {
                    upData();
                }
            }
        }
        loginRequest();
    }

    public void upData() {
        if (allMoneyBean.getBalancePercent() != 0) {
            beanLists.add(new TestBean("可用余额", allMoneyBean.getBalancePercent(), 0xffF77F96));
        }
        if (allMoneyBean.getInvestPercent() != 0) {
            beanLists.add(new TestBean("在投本金", allMoneyBean.getInvestPercent(), 0xff6ED3D6));
        }
        if (allMoneyBean.getInvestingPercent() != 0) {
            beanLists.add(new TestBean("投资冻结", allMoneyBean.getInvestingPercent(), 0xffCDF0F5));
        }
        if (allMoneyBean.getWithdrawalPercent() != 0) {
            beanLists.add(new TestBean("提现冻结", allMoneyBean.getWithdrawalPercent(), 0xffFFBDCE));
        }

        Collections.sort(beanLists, new Comparator<TestBean>() { //数字排序
            @Override
            public int compare(TestBean lhs, TestBean rhs) {
//                    return (int) rhs.percent - (int) lhs.percent;//从大到小
                return (int) lhs.percent - (int) rhs.percent;//从小到大
            }
        });

        if (beanLists.isEmpty()) {
            mChartView.setVisibility(View.GONE);
        } else {
            mChartView.setVisibility(View.VISIBLE);
        }
        int fontSize[] = new int[]{150, 160, 170, 180};
        ArrayList<ChartProp> acps = mChartView.createCharts(beanLists.size());
        int size = acps.size();
        for (int i = 0; i < size; i++) {
            ChartProp chartProp = acps.get(i);
            chartProp.setmRlength(fontSize[i+ (4-size)]);
            chartProp.setColor(beanLists.get(i).color);
            chartProp.setPercent((beanLists.get(i).percent / 100));
            chartProp.setName(beanLists.get(i).name);
            chartProp.setFontSize(30);
        }
        zong_income.setText(TextViewUtil.getSumLength(allMoneyBean.getTotalAssert()));
        bidding_money.setText(TextViewUtil.getSumLength(allMoneyBean.getInvestAmount()));
        tv_balance.setText(TextViewUtil.getSumLength(allMoneyBean.getBalance()));
        invest_freeze.setText(TextViewUtil.getSumLength(allMoneyBean.getInvestingAmount()));
        withdraw_freeze.setText(TextViewUtil.getSumLength(allMoneyBean.getWithdrawalFrozen()));
    }

    /**
     * 网络请求
     */
    private void loginRequest() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1414");
            parameters.put("id", user.getCurrUser().getSign());
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            requen.add(request);
        }
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(AllMoneyActivity.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            dg.dismiss();
            L.d("总资产 ==========" + jobj);
            SharedPreferencesUtils.saveUserInfo(AllMoneyActivity.this, "allMoneyBean", jobj.toString());
            allMoneyBean = JSON.parseObject(jobj.toString(), AllMoneyBean.class);
            if (allMoneyBean.getCode() == -1) {
                upData();
            }
        }
    };

    class TestBean implements Serializable {
        public String name;
        public float percent;
        public int color;

        public TestBean(String name, float percent, int color) {
            this.name = name;
            this.percent = percent;
            this.color = color;
        }

        @Override
        public String toString() {
            return "TestBean{" +
                    "name='" + name + '\'' +
                    ", percent=" + percent +
                    ", color=" + color +
                    '}';
        }
    }
}
